<template>
  <el-dialog
    :visible="operatorDialog"
    :before-close="handleClose"
    :show-close="true"
    :class="{'mobile-el-dialog-form': showMobilePage}"
    class="small-common-dialog-size operator-dialog"
    @closed="clearValidateInfo"
  >
    <Title :title="setType? '设置协作部门' : '设置协作人'" style="margin-bottom:12px" font-size="16px"/>
    <el-form ref="formRef" :rules="rules" :model="formData" :label-width="setType? '110px' : '100px'" class="form" label-position="right">
      <el-form-item prop="type" label="设置方式">
        <el-select
          v-model="formData.type"
          class="width240"
          size="small"
          placeholder="请选择"
          @change="typeChange">
          <el-option
            v-for="(item) in typeList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="setType === 0 && showOld" label="原协作人" prop="oldAssociate">
        <selectWithUserLoad
          v-model="formData.oldAssociate"
          :multiple="false"
          :extend-params="{
            type: 1,
          }"
          key-name="id"
          class="width240"
          label-name="userName"
          filterable
        />
      </el-form-item>
      <el-form-item v-if="setType === 0" :label="`${showOld ? '新' : ''}协作人`" prop="associate">
        <selectWithUserLoad
          v-model="formData.associate"
          :multiple="true"
          :extend-params="{
            type: 1,
          }"
          key-name="id"
          class="width240"
          label-name="userName"
          filterable
        />
      </el-form-item>
      <el-form-item v-if="setType === 1 && showOld" label="原协作部门" prop="oldCooDepartment">
        <el-cascader
          v-model="formData.oldCooDepartment"
          :show-all-levels="false"
          :options="deptTreeList"
          :props="{
            emitPath:false,
            value: 'id',
            label: 'name',
            checkStrictly: true,
            multiple: false,
          }"
          class="width240"
          placeholder="请选择所属部门"
          size="small"
          collapse-tags
          filterable
          clearable
        >
          <template slot-scope="{ data }">
            <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
              <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
              <span class="inline-tag ellipsisOne">{{ data.name }}</span>
            </el-tooltip>
            <span v-else>{{ data.name }}</span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item v-if="setType === 1" :label="`${showOld ? '新' : ''}协作部门`" prop="cooDepartment">
        <el-cascader
          v-model="formData.cooDepartment"
          :show-all-levels="false"
          :options="deptTreeList"
          :props="{
            emitPath: false,
            value: 'id',
            label: 'name',
            checkStrictly: true,
            multiple: true,
          }"
          class="width240"
          placeholder="请选择所属部门"
          size="small"
          collapse-tags
          filterable
          clearable
        >
          <template slot-scope="{ data }">
            <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
              <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
              <span class="inline-tag ellipsisOne">{{ data.name }}</span>
            </el-tooltip>
            <span v-else>{{ data.name }}</span>
          </template>
        </el-cascader>
      </el-form-item>
    </el-form>
    <div class="center btns">
      <el-button class="ok submit-btn" type="primary" size="small" @click="submit">确定<i v-if="submitLoading" class="el-icon-loading"/></el-button>
      <el-button class="back-btn cancel-btn-style" size="small" @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Title from '@/components/Title';
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { getDepartmentAll } from '@/api/config';
import { setAssociate, setCooDepartment } from '@/api/customer';
import { mapState } from 'vuex';
export default {
  components: { Title, SelectWithUserLoad },
  data() {
    return {
      submitLoading: false,
      operatorDialog: false,
      formData: {
        type: 0,
        oldCooDepartment: '', // 旧协作部门
        cooDepartment: [],
        oldAssociate: '', // 旧协作人
        associate: []
      },
      deptTreeList: [], // 部门列表
      typeList: [
        { value: 0, label: '新增' },
        { value: 1, label: '替换' },
        { value: 2, label: '移除' },
        { value: 3, label: '覆盖' }
      ],
      setType: 0,
      ids: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    showOld() {
      return this.formData.type === 1;
    },
    rules() {
      if (this.setType === 0) {
        return {
          type: [{ required: true, trigger: 'change', validator: this.validateValue('请选择设置方式') }],
          oldAssociate: [{ required: true, trigger: 'change', validator: this.validateValue('请选择原协作人') }],
          associate: [{ required: true, trigger: 'change', validator: this.validateArr(`请选择${this.showOld ? '新' : ''}协作人`) }]
        };
      } else {
        return {
          type: [{ required: true, trigger: 'change', validator: this.validateValue('请选择设置方式') }],
          oldCooDepartment: [{ required: true, trigger: 'change', validator: this.validateValue('请选择原协作部门') }],
          cooDepartment: [{ required: true, trigger: 'change', validator: this.validateArr(`请选择${this.showOld ? '新' : ''}协作部门`) }]
        };
      }
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  methods: {
    validateValue(msg) {
      return (rule, value, callback) => {
        if (value || value === 0) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    },
    validateArr(msg) {
      return (rule, value, callback) => {
        if (value && value.length) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    },
    openDialog(ids, setType) {
      this.ids = ids;
      this.setType = Number(setType);// 0 协作人 1协作部门
      this.operatorDialog = true;
    },
    // 获取部门
    queryDeptTreeList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    submit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const setApi = this.setType ? setCooDepartment : setAssociate;
          this.submitLoading = true;
          const data = Object.assign({}, this.formData);
          data.ids = this.ids;
          setApi(data).then(res => {
            this.submitLoading = false;
            this.$message.success('设置成功');
            this.$emit('updateList');
            this.handleClose();
          }).catch(err => {
            this.submitLoading = false;
            console.log(err);
          });
        } else {
          this.$message.warning('请检查信息是否填写完整');
          return;
        }
      });
    },
    typeChange() {
      setTimeout(() => {
        this.clearValidateInfo();
      }, 0);
    },
    handleClose() {
      this.operatorDialog = false;
      this.formData = {
        type: 0,
        oldCooDepartment: '', // 旧协作部门
        cooDepartment: [],
        oldAssociate: '', // 旧协作人
        associate: []
      };
      this.setType = 0;
    },
    clearValidateInfo() {
      this.$refs.formRef.clearValidate();
    }
  }
};
</script>
<style lang="scss" scoped>
.operator-dialog{
  &::v-deep {
    .el-dialog__body{
      padding: 16px 24px 24px !important;
    }
    .el-form-item__label{
      padding: 0 12px 0 8px;
    }
    .filterableSelect{
      width: 90%;
    }
    .ps--active-y {
      padding-right: 10%;
    }
    .el-select__input {
      min-width: 80px;
    }
    .el-select__tags-text {
      color: #406EFF !important;
    }
  }
  .form{
    margin-top: 17px;
    &::v-deep {
      .el-tag.el-tag--info{
        display: flex;
        color: #406EFF;
        align-items: center;
      }
      .el-select .el-tag__close.el-icon-close{
        right: 0;
      }
      .el-select__tags-text{
        display: inline-block;
        max-width: 160px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
  .btns{
    padding-top: 10px;
  }
  .width240 {
    width: 240px;
    & ::v-deep {
      .el-input__inner {
        width: 240px;
      }
      .el-input{
        width: 240px;
      }
    }
  }
  .center{
    display: flex;
    justify-content: center;
  }
}
</style>
